<?php

namespace app\index\controller;

use app\index\controller\Base;
use think\Cache;
use think\Cookie;

class Everyone extends Base {

    /**
     * @title 获取邮箱验证码
     * @method post
     * @params imagecode
     * @params email
     */
    public function email_code_send() {

        $imagecode = input('post.imagecode', '');
        $email = input('post.email', '');

        // 先要判断图形码是否输入正确
        if (!captcha_check($imagecode)) {
            $this->error('图形验证码不匹配或已过期');
        }

        // 发送邮件
        // 随机生成一个位数字
        $active_code = mt_rand(1000, 9999);

        $returnEmail = sendRegEmail($email, $email, $active_code);
        if (is_bool($returnEmail) && $returnEmail) {

            // 使用email 做为key保存，cache保存到服务器 10分钟
            cache($email, $active_code, 600);

            $mail = explode('@', $email)[1];
            $this->success('邮箱验证码发送成功，邮箱账号是：' . $email . '<br />请<a href="http://mail.' . $mail . ' ">进入邮箱</a>查看验证码', '');
        } else {
            $this->error($returnEmail);
        }
    }

    /**
     * @title 使用QQ方式登录 
     */
    public function qq_login() {
        $oauth = new \qq_connect\Oauth();
        $oauth->qq_login();
    }

    /**
     * @title QQ登录回调
     */
    public function qq_callback() {

        //请求accesstoken
        $oauth = new \qq_connect\Oauth();
        $accesstoken = $oauth->qq_callback();

        //获取open_id
        $openid = $oauth->get_openid();


        if ($openid) {
            // // 在数据库里查找$openid

            $one = db('member')->where('openid_qq', $openid)->find();
            if ($one) {
                // 老用户
                // 保存cookie 然后跳转
                $token = uniqid();
                cookie(APP_THEME . 'token', $token);

                cache($token, [
                    'id' => $one['id'],
                    'nickname' => $one['nickname'],
                    'avatar' => $one['avatar'],
                    'sex' => $one['sex'],
                        ], 3600 * 24 * 7);

                $this->success('', APP_HOST . APP_URL);
            } else {
                // 新用户
                // 获取新用户的基本信息
                //根据accesstoken和open_id获取用户的基本信息
                $qc = new \qq_connect\QC($accesstoken, $openid);
                $userinfo = $qc->get_user_info();

                if ($userinfo['ret'] == 0) {

                    // 添加到数据库
                    $insert_id = db('member')->insertGetId([
                        'create_time' => time(),
                        'update_time' => time(),
                        'nickname' => $userinfo['nickname'],
                        'avatar' => $userinfo['figureurl_qq_2'],
                        'sex' => (int) $userinfo['gender_type'],
                        'city' => $userinfo['city'],
                        'openid_qq' => $openid,
                    ]);


                    // 保存cookie 然后跳转
                    $token = uniqid();
                    cookie(APP_THEME . 'token', $token);

                    cache($token, [
                        'id' => $insert_id,
                        'nickname' => $userinfo['nickname'],
                        'avatar' => $userinfo['figureurl_qq_2'],
                        'sex' => $userinfo['gender_type'],
                            ], 3600 * 24 * 7);

                    $this->success('', APP_HOST . APP_URL);
                } else {
                    $this->error($userinfo['msg'], url('everyone/login'));
                }
            }
        } else {

            $this->error('openid获取失败');
        }

        //设置有效时长(7天)
        // cookie('accesstoken', $accesstoken, 24 * 60 * 60 * 7);
        // cookie('openid', $openid, 24 * 60 * 60 * 7);
    }

    /**
     * @title 从回复的昵称跳转到个人主页
     */
    public function jump() {

        $username = trim(input('get.username', ''));

        $id = db('member')->where('nickname', $username)->value('id');

        if ($id) {
            $this->redirect(url('portal/' . $id));
        }
    }

    /**
     * @title 签到活跃榜（异步）
     */
    public function sign_top() {

        // 今天0点0分0秒时间戳
        $today = strtotime(date("Y-m-d", time()));

        // 最新签到
        $lists_new = db('member_sign')
                ->alias('a')
                ->field('a.member_id as uid,a.num as days,a.create_time as time,m.nickname,m.avatar,max(a.create_time) as max_time')
                ->where('a.create_time', '>', $today)
                ->join('member m', 'm.id = a.member_id', 'LEFT')
                ->order('a.create_time desc')
                ->group('a.member_id,a.num,a.create_time,m.nickname,m.avatar')
                ->limit(20)
                ->select();
        foreach ($lists_new as $key => $value) {
            if (!empty($value['avatar']))
                $lists_new[$key]['avatar'] = res_http($value['avatar']);
            else
                $lists_new[$key]['avatar'] = res_http('avatar.jpg');
        }
        // 今日最快
        $lists_new2 = db('member_sign')
                ->alias('a')
                ->field('a.member_id as uid,a.num as days,a.create_time as time,m.nickname,m.avatar,max(a.create_time) as max_time')
                ->where('a.create_time', '>', $today)
                ->join('member m', 'm.id = a.member_id', 'LEFT')
                ->order('a.create_time asc')
                ->group('a.member_id,a.num,a.create_time,m.nickname,m.avatar')
                ->limit(20)
                ->select();
        foreach ($lists_new2 as $key => $value) {
            if (!empty($value['avatar']))
                $lists_new2[$key]['avatar'] = res_http($value['avatar']);
            else
                $lists_new2[$key]['avatar'] = res_http('avatar.jpg');
        }


        // 签到最多
        $lists_new3 = db('member_sign')
                ->alias('a')
                ->field('a.member_id as uid,a.num as days,a.create_time as time,m.nickname,m.avatar,max(a.num) as max_num')
                ->where('a.create_time', '>', $today)
                ->join('member m', 'm.id = a.member_id', 'LEFT')
                ->order('a.num desc')
                ->group('a.member_id,a.num,a.create_time,m.nickname,m.avatar')
                ->limit(20)
                ->select();
        foreach ($lists_new3 as $key => $value) {
            if (!empty($value['avatar']))
                $lists_new3[$key]['avatar'] = res_http($value['avatar']);
            else
                $lists_new3[$key]['avatar'] = res_http('avatar.jpg');
        }

        return ['code' => 0, 'msg' => '', 'data' => [$lists_new, $lists_new2, $lists_new3]];
    }

    /**
     * @title 个人主页
     */
    public function portal($id) {



        $member = member_is_login();
        if (is_array($member)) {
            $member_id = $member['id'];
        } else {
            $member_id = 0;
        }

        if (empty($id)) {

            if ($member_id)
                $id = $member_id;
            else
                exit;
        }

        $wheres[] = ['a.id', '=', $id];
        $one = model('member')->model_where($wheres)->find();

        if (is_object($one)) {
            $one = $one->toArray();
        } else {
            $this->error('用户不存在或已禁用');
        }

        $one['follow_type'] = model('member_follow')->follow_type($one['id'], $member_id);

        $this->assign($one);


        // 加载最近的帖子
        $recent_thread_lists = model('thread')->where('member_id', $id)->limit(20)->select();
        $this->assign('recent_thread_lists', $recent_thread_lists);


        // 加载最近的回答
        $where = [
                ['a.member_id', '=', $id]
        ];
        $recent_comment_lists = model('thread_comment')->model_where($where)->limit(10)->select();
        $this->assign('recent_comment_lists', $recent_comment_lists);



        return view();
    }

    public function index() {


        return view();
    }

    /**
     * @title 密码重设
     */
    public function repass() {



        // 两个隐藏域
        $token = input('post.token');
        $email = input('post.email');

        // 验证token对不对
        if (cache($email) != $token || empty($token) || empty($email)) {
            $this->error('无权修改');
        }



        $pass = input('post.pass');
        $repass = input('post.repass');
        $imagecode = input('post.imagecode');

        // 先要判断图形码是否输入正确
        if (!captcha_check($imagecode)) {
            $this->error('图形验证码不匹配或已过期');
        }

        // 
        if ($pass != $repass) {
            $this->error('两次输入的密码不一致');
        }

        // 修改
        $affect_rows = db('member')->where('email', $email)->setField('password', my_md5($pass));

        if ($affect_rows) {
            $this->success('修改成功', 'everyone/login');
        }
    }

    /**
     * @title 忘记密码
     */
    public function forget() {

        if (request()->isPost()) {

            $email = request()->post('email');
            $imagecode = request()->post('imagecode');
            $vercode = request()->post('vercode');

            // 查看vercode是否正确
            $code = cache($email);

            if ($vercode == $code) {

                // 生成一个临时token 放到url中
                $token = uniqid();

                // 5分钟验证有效期
                cache($email, $token, 300);

                $this->success('验证成功，点击确定进入重设你的密码', url('everyone/forget', ['token' => $token, 'email' => $email]));
            } else {
                return ['code' => 1, 'msg' => '验证码输入有误'];
            }
        } else {

            $email = request()->get('email');
            $token = request()->get('token');

            if ($email && $token) {

                // 验证token对不对
                if (cache($email) != $token) {
                    $this->error('无权修改');
                }


                // 加载昵称 
                $this->assign('token', $token);
                $this->assign('email', $email);
                $this->assign('nickname', db('member')->where('email', $email)->value('nickname'));
            }

            return view();
        }
    }

    /**
     * @title 退出
     */
    public function logout() {

        $token = cookie(APP_THEME . 'token_member');

        Cache::rm($token);

        Cookie::delete(APP_THEME . 'token_member');

        $this->redirect('everyone/login');
    }

    /**
     * @title 登录
     */
    public function login() {


        if (request()->isPost()) {

            // 先要判断图形码是否输入正确
            if (!captcha_check(request()->post('imagecode'))) {
                $this->error('图形验证码不匹配或已过期');
            }

            //  预处理
            $post = request()->post();
            foreach ($post as $key => $value) {
                $post[$key] = trim($value);
            }

            $msg = model('member')->login($post);

            if (empty($msg)) {
                // 
                // 如果存在redirect
                if (request()->get('redirect')) {
                    $this->success('', url(request()->get('redirect')));
                } else {
                    $this->success('', APP_URL . '/');
                }
            } else {
                $this->error($msg);
            }
        } else {

            return view();
        }
    }

    /**
     * @title 注册 
     */
    public function reg() {
        
        // 是否开启注册邮箱验证
        $reg_email_check = config('?base.reg_email_check') ? config('base.reg_email_check'): 1;
        $this->assign('reg_email_check', $reg_email_check);


        if (request()->isPost()) {            
            
            $imagecode = input('post.imagecode', '');

            // 先要判断图形码是否输入正确
            if (!$reg_email_check && !captcha_check($imagecode)) {
                $this->error('图形验证码不匹配或已过期');
            }

            //  后端验证
            $post = request()->post();
            foreach ($post as $key => $value) {
                $post[$key] = trim($value);
            }

            //
            $email_count = db('member')->where('email', $post['email'])->count();
            if ($email_count) {
                $this->error('你填写的邮箱已经被注册了');
            }
            $nickname_count = db('member')->where('nickname', $post['nickname'])->count();
            if ($nickname_count) {
                $this->error('你填写的昵称已经被其他人使用了');
            }


            //                 
            $msg = model('member')->reg($post);
            if (is_numeric($msg) && $msg > 0) {
                $this->success("注册成功");
            } else {
                $this->error($msg);
            }
        } else {


            return view();
        }
    }

    /**
     * @title 新注册用户激活账号
     */
    public function activate() {

        $code = input('get.code', '');

        if ($code) {

            $affect_rows = db('member')->where('active_code', $code)->setField('status', 1);

            if ($affect_rows) {
                $this->success('激活成功', config('base.domain'));
            } else {
                $this->error('已经激活过了');
            }
        }
    }

    /**
     * @title 帖子浏览量
     * @params id
     */
    public function thread_hits($id = 0) {
        if ($id) {
            db('thread')->where('id', $id)->setInc('hits');
        }
    }

}
